package main

import (
	"sync"
	"time"

	"gitee.com/fcsvr/fancy/fclog"
	"gitee.com/fcsvr/fancy/fcnet"
)

type PingRouter struct {
	fcnet.BaseRouter
}

func (this *PingRouter) Handle(req *fcnet.Req) {
	fclog.Debug("PingRouter Handle")
	fclog.Debug("Recv from cli: msgid = %d, data = %s", req.GetMsgID(), string(req.GetData()))
	err := req.GetConn().SendMsg(1, []byte("Ping"))
	if err != nil {
		fclog.Error("PingRouter Handle: send msg err = %s", err)
	}
}

type HelloRouter struct {
	fcnet.BaseRouter
}

func (this *HelloRouter) Handle(req *fcnet.Req) {
	fclog.Debug("HelloRouter Handle")
	fclog.Debug("Recv from cli: msgid = %d, data = %s", req.GetMsgID(), string(req.GetData()))
	err := req.GetConn().SendMsg(2, []byte("Hello"))
	if err != nil {
		fclog.Error("HelloRouter Handle: send msg err = %s", err)
	}
}

func DoConnectionStart(conn *fcnet.Conn) {
	fclog.Debug("DoConnectionStart")

	conn.SetProperty("Name", "FancyGo")
	conn.SetProperty("Home", "fancygo.net")
	err := conn.SendMsg(3, []byte("DoConnection start"))
	if err != nil {
		fclog.Error("DoConnectionStart: err = %s", err)
	}
}

func DoConnectionStop(conn *fcnet.Conn) {
	fclog.Debug("DoConnectionStop")
	if name, err := conn.GetProperty("Name"); err == nil {
		fclog.Info("DoConnectionStop: conn get property name = %s", name)
	}
	if home, err := conn.GetProperty("Home"); err == nil {
		fclog.Info("DoConnectionStop: conn get property name = %s", home)
	}
}

type Hello struct {
	S string
}

type User struct {
	ID       int
	Name     string
	Birthday time.Time
	Lv       int
	H        Hello
}

type Game struct {
	Users []User
	lock  sync.RWMutex
}

func NewGame() *Game {
	g := &Game{
		Users: make([]User, 0, 0),
	}
	return g
}

var FC_Game Game

type Reply struct {
	Ret  int
	User *User
}

type AddUserRouter struct {
	fcnet.BaseRouter
	Arg   *User
	Reply *Reply
}

func (this *AddUserRouter) GetArg() any {
	return this.Arg
}
func (this *AddUserRouter) SetArg(arg any) {
	this.Arg = arg.(*User)
}

func (this *AddUserRouter) Handle(req *fcnet.Req) {
	fclog.Debug("AddUserRouter Handle")
	fclog.Debug("Recv from cli: msgid = %d, data = %+v", req.GetMsgID(), this.Arg)

	FC_Game.lock.Lock()
	defer FC_Game.lock.Unlock()
	FC_Game.Users = append(FC_Game.Users, *this.Arg)
	this.Arg.Lv = 19

	reply := &Reply{
		Ret:  1,
		User: this.Arg,
	}
	err := req.GetConn().SendMsg(2, reply)
	if err != nil {
		fclog.Error("HelloRouter Handle: send msg err = %s", err)
	}
}

func main() {
	fclog.Info("Hello, FancyGo, This is FCSVR")
	server := fcnet.NewServer("[FCSvr]")
	server.SetOnConnStart(DoConnectionStart)
	server.SetOnConnStop(DoConnectionStop)

	//server.AddRouter(1, &PingRouter{})
	//server.AddRouter(2, &HelloRouter{})
	server.AddRouter(3, &AddUserRouter{})
	server.Serve()
	for {
		time.Sleep(5 * time.Second)
	}
}
